package com.normal.zbase.impl.tools.utils

import android.util.Log
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

/**
 * 三疯
 * *************************
 *
 * *************************
 */
object TimerUitls {
    var timerSecnd = MutableLiveData<Int>()
    private lateinit var countDownJob: Job
    private var time = 17

    private fun start(lifecycleOwner: LifecycleOwner) {
        countDownJob = lifecycleOwner.lifecycleScope.launch {
            // 在这个范围内启动的协程会在Lifecycle被销毁的时候自动取消
            flow {
                (time downTo 0).forEach {
                    delay(1000)
                    emit(it)
                }
            }.onStart {

            }.onCompletion {

            }.catch {
                //错误
                Log.e("zxy", it.message ?: "Unkown Error")
            }.collect {
                timerSecnd.postValue(it)
            }
        }
    }

    fun reStart(lifecycleOwner: LifecycleOwner) {
        if (this::countDownJob.isInitialized) {
            cancel()
            start(lifecycleOwner)
        } else {
            start(lifecycleOwner)
        }
    }

    fun cancel() {
        if (this::countDownJob.isInitialized)
            countDownJob.cancel()
    }
}